'''

    The Crypt Pages

'''

import json 

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core import serializers

from models import Project, Lib, Char, Set, Prop, Sequence, Shot

def main(request):
    MGL = '/u/local/workspace' in __file__
    return render_to_response("the_crypt/main.html", {"MGL":MGL})

def welcome(request):
    MGL = '/u/local/workspace' in __file__
    return render_to_response("the_crypt/welcome.html", {"MGL":MGL})



#
#--- TREE
#
class TreeItem(object):
    def __init__(self, modelName, o):
        self._o = o
        self._modelName = modelName
        self._subItems = []
    
    def extend(self, subItems):
        self._subItems.extend(subItems)
    
    def _my_data(self):
        ret = {
            "data": self._o and self._o.name or self._modelName,
            "attr": {
                "model": self._modelName,
                "pk": self._o and self._o.pk or None,
            },
        }
        return ret
        
    def data(self):
        ret = self._my_data()
        if self._subItems:
            ret["children"] = [ sub.data() for sub in self._subItems ]
        else:
            ret["state"] = "closed"
        return ret

class TreeMenuItem(object):
    def __init__(self, name, label):
        self._name = name
        self._label = label
        self._subItems = []
        
    def extend(self, subItems):
        self._subItems.extend(subItems)
    
    def data(self):
        data = {
            # The item label
            "label"             : self._label,
            # The function to execute upon a click
            "action"            : "on_tree_action("+`self._name`+", n)",   # The javascript to execute.
            # All below are optional 
            "_disabled"         : False,	# clicking the item won't do a thing
            "_class"            : "toto",	# class is applied to the item LI node
            "separator_before"  : False,	# Insert a separator before the item
            "separator_after"   : False,	# Insert a separator after the item
            # false or string - if does not contain `/` - used as classname
            "icon"              : False,
            #"submenu"           : [ sub.data() for sub in self._subItems ]
        }
        return self._name, data

class TreeMenu(object):
    class _strKey( str ):
        '''Utility to make dict sorted by add order.'''
        _ID = 0
        def __init__(self, *args, **kwargs):
            str.__init__(*args, **kwargs)
            self._id = self._ID
            self._ID += 1
        def __hash__(self):
            print 'id of', `self`, 'is', self._id
            return self._id
        
    def __init__(self, items=[] ):
        self._items = items
    
    def extend(self, items):
        self._items.extend(items)
    
    def data(self):
        ret = {}
        for i in self._items:
            name, data = i.data()
            ret[self._strKey(name)] = data
        return ret
    
def get_projects( pk=None ):
    '''
    Return all projects items.
    '''
    ret = [ TreeItem("Project", o) for o in Project.objects.all() ]
    return ret
    
def get_project_items( pk ):
    '''
    Return items in the given project.
    '''
    libs = [ TreeItem("Lib", o) for o in Lib.objects.filter(project=pk) ]
    seqs = [ TreeItem("Sequence", o) for o in Sequence.objects.filter(project=pk) ]
    if len(libs) > 1:
        libGroup = TreeItem("Libs",None)
        libGroup.extend(libs)
        ret = [libGroup]
    else:
        ret = libs
    ret.extend(seqs)
    return ret

def get_lib_items(pk):
    '''
    Return items in the given lib.
    '''
    chars = TreeItem("Chars", None)
    chars.extend([ TreeItem("Chars", o) for o in Char.objects.filter(lib=pk) ])

    sets = TreeItem("Sets", None)
    sets.extend([ TreeItem("Set", o) for o in Set.objects.filter(lib=pk) ])

    props = TreeItem("Props", None)
    props.extend([ TreeItem("Prop", o) for o in Prop.objects.filter(lib=pk) ])
    
    return [chars, sets, props]

def get_sequence_items(pk):
    '''
    Return items in the given sequence.
    '''
    shots = [ TreeItem("Shot", o) for o in Shot.objects.filter(sequence=pk) ]
    return shots

def get_loader( model ):
    return {
        'Projects': get_projects,
        'Project': get_project_items,
        'Lib': get_lib_items,
        'Sequence': get_sequence_items,
    }.get(model)
    
def tree_open(request):
    model = request.GET.get("model")
    pk = request.GET.get("pk")
    #print model, pk
    
    try:
        loader = get_loader(model)
        if loader:
            children = [ c.data() for c in loader(pk) ]
        else:
            children = []
    except Exception, err:
        print err
        children = []
    
    children = json.encoder.JSONEncoder().encode(children)
    return HttpResponse(
        children, mimetype="application/json"
    )

def tree_menu(request):
    model = request.GET.get("model")
    pk = request.GET.get("pk")

    menu = TreeMenu([
        TreeMenuItem("actionA", "Action A"),
        TreeMenuItem("actionB", "Action B"),
        TreeMenuItem("actionC", "Action C"),
    ])
    menu = json.encoder.JSONEncoder().encode(menu.data())

    return HttpResponse(
        menu, mimetype="application/json"
    )

def tree_action(request):
    model = request.GET.get("model")
    pk = request.GET.get("pk")
    action = request.GET.get("action")
    
    try:
        ret = {"url": "/admin/the_crypt/"+model.lower()+"/"+pk+"/", "iframe" : "center" }
        ret = json.encoder.JSONEncoder().encode(ret)
        print "\n\nTREE ACTION:", "ACTION", action, "ON", model, "with pk =", pk, "\n\n"
        return HttpResponse(
            ret, mimetype="application/json"
        )
    except Exception, err:
        print '\n\n', str(err)

